#ifdef WEB_ENABLE
//logMessage(LOGLEVEL_DEBUG, "WEB", "", "");

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte WEBMACAddress[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
int WEBServerPort = 8080;
IPAddress WEBLogServer(192,168,1,100);
IPAddress WEBIPAddress(192,168,1,177);
unsigned long WEBPreviousMillis;

// Initialize the Ethernet client library
// with the IP address and port of the server 
// that you want to connect to (port 80 is default for HTTP):
EthernetClient WEBclient;
EthernetServer WEBServer(WEBServerPort);

void setupWeb() {
	logMessage(LOGLEVEL_INFO, "WEB", "setup Web", "");
	// start the Ethernet connection:
	Ethernet.begin(WEBMACAddress, WEBIPAddress);
	WEBServer.begin();
	// einmal "Pingen" um die NetzwerkApi zu initialisieren
	String tempTime = getWebTime();
}

String getWebTime() {
	Serial.println("connecting for getting time ...");
	String tempWebTime = "";
	if (WEBclient.connect(WEBLogServer, WEBServerPort)) {
		Serial.println("connected");
		String tempRequest = "GET /primaKlima/syncPoint.php HTTP/1.0";
		WEBclient.println(tempRequest);
		WEBclient.println();
		//WEBclient.stop();
		delay(300);
		//Serial.println("WEBclient stoped");
		if (WEBclient.available()) {
			Serial.println("read time ...");
			long tempTimeout = millis();
			for (;;) {
				if ((millis()-tempTimeout>WEB_TIMEOUT)) {
					Serial.println("timeout!");
					break;
				}
				char c = WEBclient.read();
				tempWebTime += c;

				// if the server's disconnected, stop the client:
				if (!WEBclient.connected()) {
					//Serial.println();
					Serial.println("disconnecting.");
					WEBclient.stop();
					break;
				}
			}
		}
	}

	if (tempWebTime.length() > 6) {
		return tempWebTime.substring(tempWebTime.length()-6);
	}
	return tempWebTime;
}

void logToWebDelay() {
	unsigned long tempCurrentMillis = millis();
	if((tempCurrentMillis - WEBPreviousMillis) > WEB_LOGDELAY || WEBPreviousMillis == 0) {
		WEBPreviousMillis = tempCurrentMillis;
		_logToWeb();
	}
}

void _logToWeb() {
	Serial.println("_logToWeb: connecting ...");
	if (WEBclient.connect(WEBLogServer, WEBServerPort)) {
		Serial.println("_logToWeb: connected");
		String tempRequest = "GET /primaKlima/logChart.php?time=";
		tempRequest += getTimeForWebFormatted();

		// SYSTEM 2
		tempRequest += "&actualLightSystem2=";
		tempRequest += (int)getStatusOfSystem2(SENSORS_LIGHT2_PIN);
		tempRequest += "&givenLightSystem2=";
		tempRequest += (int)getStatusOfSystem(getSystemLightOn(SYSTEM2), getTimerDuration(SYSTEM2));
		tempRequest += "&tempSystem2=";
		tempRequest += (int)getLM35Temperature(2);

		WEBclient.println(tempRequest);
		WEBclient.println();
		WEBclient.stop();
	}
	else {
		// kf you didn't get a connection to the server:
		Serial.println("_logToWeb: connection failed");
	}
}

void notifyToWeb(int aStatus, int aSystem) {
	Serial.println("notifyToWeb: connecting ...");

	if (WEBclient.connect(WEBLogServer, WEBServerPort)) {
		//Serial.println("connected");
		String tempRequest = "GET /primaKlima/alarmNotifier.php?system=";
		tempRequest += (int)aSystem;
		tempRequest += "&status=";
		tempRequest += (int)aStatus;
		Serial.println(tempRequest);

		WEBclient.println(tempRequest);
		WEBclient.println();
		WEBclient.stop();
	}
	else {
		// kf you didn't get a connection to the server:
		Serial.println("notifyToWeb: connection failed");
	}
}

void printWeb() {
	EthernetClient tempClient = WEBServer.available();
	if (tempClient) {
		Serial.println("printWeb: client connected");
		String tempInputString = "";
		// an http request ends with a blank line
		boolean tempCurrentLineIsBlank = true;
		while (tempClient.connected()) {
			if (tempClient.available()) {
				char c = tempClient.read();
				// if you've gotten to the end of the line (received a newline
				// character) and the line is blank, the http request has ended,
				// so you can send a reply
				if (c == '\n' && tempCurrentLineIsBlank) {
					_readHeader(tempInputString);
					tempClient.println(_getHTTPResponseHeader());
					tempClient.println();

					// GLOBAL
#ifdef TIME_ENABLE
					tempClient.print("Uhrzeit: ");
					tempClient.print(getTimeFormatted());
					tempClient.print("<br />");
#endif
#ifdef STORAGE_ENABLE
					tempClient.print("Resets: ");
					tempClient.print(getStorageValue(LOGGER_EEPROM_FACILITY));
					tempClient.print("<br />");
#endif
					tempClient.print("<br />");
					// SYSTEM 1
#ifdef SENSORS_ENABLE
					tempClient.print("System 1: ");
					tempClient.print("<br />");
					tempClient.print("Licht (soll): ");
					tempClient.print(getStatusOfSystem(getSystemLightOn(SYSTEM1), getTimerDuration(SYSTEM1)));
					tempClient.print("<br />");
					tempClient.print("Licht (ist): ");
					tempClient.print(getStatusOfSystem2(SENSORS_LIGHT1_PIN));
					tempClient.print("(");
					tempClient.print(analogRead(SENSORS_LIGHT1_PIN));
					tempClient.print(")");
					tempClient.print("<br />");
#endif
#ifdef STORAGE_ENABLE
					tempClient.print("Licht an: ");
					tempClient.print(getStorageValue(TIMER_SYSTEM1_LIGHTON_FACILITY));
					tempClient.print("<br />");
					tempClient.print("Licht Dauer: ");
					tempClient.print(getStorageValue(TIMER_SYSTEM1_LIGHTDURATION_FACILITY));
					tempClient.print("<br />");
#endif
#ifdef LM35_ENABLE
					tempClient.print("Raumtemperatur: ");
					tempClient.print(getLM35Temperature(0));
					tempClient.print("C (");
					tempClient.print(getLM35TemperatureMin(0));
					tempClient.print("/");
					tempClient.print(getLM35TemperatureMax(0));
					tempClient.print(")<br />");
					tempClient.print("Raumtemperatur: ");
					tempClient.print(getLM35Temperature(1));
					tempClient.print("C (");
					tempClient.print(getLM35TemperatureMin(1));
					tempClient.print("/");
					tempClient.print(getLM35TemperatureMax(1));
					tempClient.print(")<br />");
#endif

					// SYSTEM 2
#ifdef SENSORS_ENABLE
					tempClient.print("<br />");
					tempClient.print("System 2: ");
					tempClient.print("<br />");
					tempClient.print("Licht (soll): ");
					tempClient.print(getStatusOfSystem(getSystemLightOn(SYSTEM2), getTimerDuration(SYSTEM2)));
					tempClient.print("<br />");
					tempClient.print("Licht (ist): ");
					tempClient.print(getStatusOfSystem2(SENSORS_LIGHT2_PIN));
					tempClient.print("(");
					tempClient.print(analogRead(SENSORS_LIGHT2_PIN));
					tempClient.print(")");
					tempClient.print("<br />");
#endif
#ifdef STORAGE_ENABLE
					tempClient.print("Licht an: ");
					tempClient.print(getStorageValue(TIMER_SYSTEM2_LIGHTON_FACILITY));
					tempClient.print("<br />");
					tempClient.print("Licht Dauer: ");
					tempClient.print(getStorageValue(TIMER_SYSTEM2_LIGHTDURATION_FACILITY));
					tempClient.print("<br />");
#endif
#ifdef LM35_ENABLE
					tempClient.print("Raumtemperatur: ");
					tempClient.print(getLM35Temperature(2));
					tempClient.print("C (");
					tempClient.print(getLM35TemperatureMin(2));
					tempClient.print("/");
					tempClient.print(getLM35TemperatureMax(2));
					tempClient.print(")<br />");
#endif
					// REST
#ifdef FAN_ENABLE
					tempClient.print("L�fter: ");
					tempClient.print(getFanSpeedValue());
					tempClient.println("% <br />");
#endif
#ifdef SHT15_ENABLE
					for (int i=0; i<SHT15SENSORS; i++) {
						tempClient.print("<ul>");
						tempClient.print("<li>Sensor: ");
						tempClient.println(i);
						tempClient.print("</li><ul><li>Temp: ");
						tempClient.print(getSHT15Temperature(i));
						tempClient.print("C (");
						tempClient.print(getSHT15TemperatureMin(i));
						tempClient.print("/");
						tempClient.print(getSHT15TemperatureMax(i));
						tempClient.println(")</li>");
						tempClient.print("<li>Rlf: ");
						tempClient.print(getSHT15Humidity(i));
						tempClient.println("% (");
						tempClient.print(getSHT15HumidityMin(i));
						tempClient.print("/");
						tempClient.print(getSHT15HumidityMax(i));
						tempClient.print(")</li></ul></li></ul>");
					}
#endif
					break;
				}
				else {
					tempInputString += c;
				}
				if (c == '\n') {
					tempCurrentLineIsBlank = true;
				}
				else if (c != '\r') {
					tempCurrentLineIsBlank = false;
				}
			}
		}
		// give the web browser time to receive the data
		delay(10);
		tempClient.stop();
		Serial.println("printWeb: client disconnected");
	}
}

void _readHeader(String aHeader) {
	String line = aHeader.substring(0, aHeader.indexOf('\n'));
	_extractAndExecuteCommand(line);
}

void _extractAndExecuteCommand(String aRequest) {
	int tempStart = aRequest.indexOf("?") + 1;
	int tempStop = aRequest.indexOf("HTTP") - 1;
	String tempRequest = aRequest.substring(tempStart, tempStop);

	int tempPos = tempRequest.indexOf('=');

	char tempCommand[MAX_COMMAND_SIZE];
	char tempValue[MAX_COMMAND_SIZE];

	tempRequest.substring(0,tempPos).toCharArray(tempCommand, MAX_COMMAND_SIZE);
	tempRequest.substring(tempPos + 1).toCharArray(tempValue, MAX_COMMAND_SIZE);

	_setCommand(tempCommand);
	_setValue(tempValue);
	executeCommands();
}

/*************************************** 
 * 
 * display implementations
 *
 ***************************************/

/*************************************** 
 * 
 * format functions & helpers
 *
 ***************************************/
String _getHTTPResponseHeader() {
	String tempHeader = "HTTP/1.1 200 OK\n";
	tempHeader += "Content-Type: text/html\n\n";
	return tempHeader;
}

#endif
